package cn.wjx.taobaounion.ui.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.wjx.taobaounion.R;

/**
 * @author WuChangJian
 * @date 2020/6/27 10:32
 */
public class FlowTextLayout extends ViewGroup {
    private List<String> mTextList = new ArrayList<>();
    public static final float DEFAULT_SPACE = 10;
    private float itemHorizontalSpace = DEFAULT_SPACE;
    private float itemVerticalSpace = DEFAULT_SPACE;
    private int mSelfWidth;
    private int mItemHeight;
    private OnFlowTextItemClickListener mListener;

    public FlowTextLayout(Context context) {
        this(context, null);
    }

    public FlowTextLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlowTextLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FlowLayout);
        itemHorizontalSpace = ta.getFloat(R.styleable.FlowTextLayout_itemHorizontal, DEFAULT_SPACE);
        itemVerticalSpace = ta.getFloat(R.styleable.FlowTextLayout_itemVertical, DEFAULT_SPACE);
        //LogUtils.d(this, "horizontal-->" + itemHorizontalSpace);
        //LogUtils.d(this, "vertical-->" + itemVerticalSpace);
        ta.recycle();
    }

    public boolean isEmpty() {
        return lines.isEmpty();
    }
    public void setTextList(List<String> textList) {
        removeAllViews();
        this.mTextList.clear();
        this.mTextList.addAll(textList);
        Collections.reverse(mTextList);
        //遍历内容
        for(String text : mTextList) {
            //添加子view
            //LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view,this,true);
            // 等价于
            TextView item = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view,this,false);
            item.setText(text);
            item.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mListener != null) {
                        mListener.onFlowTextItemClick(text);
                    }
                }
            });
            addView(item);
        }
    }
    // 所有行
    private List<List<View>> lines = new ArrayList<>();
    @Override
    protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        if(getChildCount() == 0) {
            return;
        }
        //这个是描述单行
        List<View> line = null;
        lines.clear();
        mSelfWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
        //LogUtils.d(this,"mSelfWidth == > " + mSelfWidth);
        //测量
        //LogUtils.d(this,"onMeasure -- > " + getChildCount());
        //测量孩子
        int childCount = getChildCount();
        for(int i = 0; i < childCount; i++) {
            View itemView = getChildAt(i);
            if(itemView.getVisibility() != VISIBLE) {
                //不需要进行测量
                continue;
            }
            //测量前
            //LogUtils.d(this,"before height -- > " + itemView.getMeasuredHeight());
            measureChild(itemView,widthMeasureSpec,heightMeasureSpec);
            //测量后
            // LogUtils.d(this,"after height -- > " + itemView.getMeasuredHeight());
            if(line == null) {
                //说明当前行为空，可以添加进来
                line = createNewLine(itemView);
            } else {
                //判断是否可以再继续添加
                if(canBeAdd(itemView,line)) {
                    //可以添加，添加去
                    line.add(itemView);
                } else {
                    //新创建一行
                    line = createNewLine(itemView);
                }
            }
        }
        mItemHeight = getChildAt(0).getMeasuredHeight();
        int selfHeight = (int) (lines.size() * mItemHeight + itemVerticalSpace * (lines.size() + 1) + 0.5f);
        //测量自己
        setMeasuredDimension(mSelfWidth,selfHeight);
    }

    private List<View> createNewLine(View itemView) {
        List<View> line = new ArrayList<>();
        line.add(itemView);
        lines.add(line);
        return line;
    }

    /**
     * 判断当前行是否可以在继续添加新数据
     * @param itemView
     */
    private boolean canBeAdd(View itemView, List<View> line) {
        // 1. 计算行宽：itemView.width + (view.size + 1)*itemHorizontalSpace
        // 2. 判断行宽和父容器的宽度
        int totalWidth = itemView.getMeasuredWidth();
        for (View view : line) {
            totalWidth += view.getMeasuredWidth();
        }
        totalWidth += (line.size() + 1) * itemHorizontalSpace;
        //LogUtils.d(this, "total width-->" + totalWidth);
        return totalWidth <= mSelfWidth;

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //摆放孩子
        //LogUtils.d(this,"onLayout -- > " + getChildCount());
        int topOffset = (int) itemHorizontalSpace;
        for(List<View> views : lines) {
            //views是每一行
            int leftOffset = (int) itemHorizontalSpace;
            for(View view : views) {
                //每一行里的每个item
                view.layout(leftOffset,topOffset,leftOffset + view.getMeasuredWidth(),topOffset + view.getMeasuredHeight());
                leftOffset += view.getMeasuredWidth() + itemHorizontalSpace;

            }
            topOffset +=  mItemHeight + itemHorizontalSpace;
        }
    }

    public void setOnFlowTextItemClickListener(OnFlowTextItemClickListener listener) {
        this.mListener = listener;
    }
    public interface OnFlowTextItemClickListener {
        void onFlowTextItemClick(String text);
    }
    public float getItemHorizontalSpace() {
        return itemHorizontalSpace;
    }

    public void setItemHorizontalSpace(float itemHorizontalSpace) {
        this.itemHorizontalSpace = itemHorizontalSpace;
    }

    public float getItemVerticalSpace() {
        return itemVerticalSpace;
    }

    public void setItemVerticalSpace(float itemVerticalSpace) {
        this.itemVerticalSpace = itemVerticalSpace;
    }
}
